<template>
	<el-upload ref="uploadRef" v-model:file-list="myFileList" :auto-upload="autoUpload" :limit="limit"
		:multiple="limit > 1" action="" :on-change="handleUploadChange" :on-exceed="handleUploadExceed"
		:before-upload="handleUploadBefore" :accept="accept" drag>
		<el-icon class="el-icon--upload">
			<ele-UploadFilled />
		</el-icon>
		<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
		<template #tip>
			<div class="el-upload__tip">{{ sizeText }},{{ acceptText }},{{ limitText }},{{ multipleText }}</div>
		</template>
	</el-upload>
</template>

<script lang="ts" setup>
// 文件上传组件,后续将拓展文件大小等业务和组件样式
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';

defineOptions({
	name: 'MkUpload',
});
// 实例
const uploadRef = ref<any>(null);
// emit
const emits = defineEmits(['uploadChange', 'uploadBefore']);

// prop
const props = withDefaults(defineProps<{ accept: string; limit: number; limitMb: number, autoUpload: boolean, triggerChange: boolean }>(), {
	accept: '*', // 默认支持所有的文件格式
	limit: 1, //默认只能上传一个文件
	limitMb: 100, //默认100MB
	autoUpload: false, // 默认不自动上传
	triggerChange: true, // 默认不触发change事件
});

const myFileList = ref<any[]>([]);
const sizeText = computed(() => `${props.limitMb ? `请上传大小不超过${props.limitMb}MB的单个文件` : '上传单个文件大小无限制'}`);
const acceptText = computed(() => `支持${props.accept === '*' ? '所有' : props.accept}格式`);
const limitText = computed(() => `最多可上传${props.limit}个文件`);
const multipleText = computed(() => `${props.limit > 1 ? '可' : '不可'}选择多个文件`);

// 通过onChanne方法获得文件列表
const handleUploadChange = (file: any, fileList: any[]) => {
	if (props.triggerChange) {
		// 限制文件类型,如果文件类型不是"*"就开启检查
		if (props.accept !== '*') {
			// 先拿到文件的后缀
			const fileNameList = file.name.split('.');
			const fileSuffix = `.${fileNameList[fileNameList.length - 1]}`;
			// 可上传的文件类型
			const fileAcceptList = props.accept.split(',');
			if (!fileAcceptList.includes(fileSuffix)) {
				// 文件列表删掉当前文件
				const index = myFileList.value.indexOf(file);
				if (index !== -1) {
					myFileList.value.splice(index, 1);
				}
				return ElMessage.error(`${file.name}不在${props.accept}格式内`);
			}
		}

		// 限制文件上传大小
		if (props.limitMb) {
			const isMoreThan = file.size / 1024 / 1024 > props.limitMb;
			if (isMoreThan) {
				// 文件列表删掉当前文件
				const index = myFileList.value.indexOf(file);
				if (index !== -1) {
					myFileList.value.splice(index, 1);
				}
				return ElMessage.error(`${file.name}上传文件大小超过${props.limitMb}MB!`);
			}
		}
		emits('uploadChange', file, myFileList.value);
	}

};

// 文件超出个数限制时的钩子
const handleUploadExceed = () => {
	ElMessage.error(`最多可上传${props.limit}个文件`);

};
/**
 * 上传前的钩子
 */
const handleUploadBefore = (file: any) => {
	// 限制文件类型,如果文件类型不是"*"就开启检查
	if (props.accept !== '*') {
		// 先拿到文件的后缀
		const fileNameList = file.name.split('.');
		const fileSuffix = `.${fileNameList[fileNameList.length - 1]}`;
		// 可上传的文件类型
		const fileAcceptList = props.accept.split(',');
		if (!fileAcceptList.includes(fileSuffix)) {
			// 文件列表删掉当前文件
			const index = myFileList.value.indexOf(file);
			if (index !== -1) {
				myFileList.value.splice(index, 1);
			}
			return ElMessage.error(`${file.name}不在${props.accept}格式内`);
		}
	}
	emits('uploadBefore', file);
};
/**
 * 选择文件
 */
const select = () => {
	if (uploadRef.value) uploadRef.value.$el.querySelector('input').click();
};
/**
 * 清空已上传文件
 */
const clearFiles = () => {
	myFileList.value = [];
	uploadRef.value.clearFiles();
};
// 暴露出去
defineExpose({
	select,
	clearFiles,
});
</script>

<style lang="scss" scoped></style>
